﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RXY_Mall.Application.Message.Dto;

namespace RXY_Mall.Application.Message
{
    public class MessageService : RXY_MallAppServiceBase, IMessageService
    {
        public IList<MessageDto> GetMessageByPage(int iDisplayStart, int iDisplayLength, string title, int status, int shop_id, out int totalCount)
        {
            iDisplayLength = iDisplayLength < 1 ? 10 : iDisplayLength;
            var list = db.gw_messages
                 .Where(m => m.shop_id == shop_id && !m.deleted)
                .Select(item => new MessageDto
                {
                    id = item.id,
                    title = item.title,
                    summary = item.summary,
                    content = item.content,
                    type = item.type,
                    status=item.status,
                    add_time=item.add_time
                });
            if (status > -1)
            {
                list = list.Where(m => m.status == status);
            }
            if (!string.IsNullOrWhiteSpace(title))
            {
                list = list.Where(m => m.title.Contains(title));
            }

            totalCount = list.Count();
            list = list.OrderBy(m => m.status).ThenByDescending(m => m.add_time).Skip(iDisplayStart).Take(iDisplayLength);
            return list.ToList();
        }

        public IList<MessageDto> GetTopMessage(int top,int shop_id, out int totalCount)
        {
            var list = db.gw_messages
                .Where(m => m.shop_id == shop_id && !m.deleted && m.status == 1)
                .Select(item=>new MessageDto {
                    id=item.id,
                    title=item.title,
                    summary=item.summary,
                    content=item.content,
                    type=item.type,
                    add_time=item.add_time
                });
            totalCount = list.Count();
            return list.OrderByDescending(m => m.add_time).Skip(0).Take(top).ToList();
        }

        public async Task<bool> ReadMessage(int shop_id)
        {
            var message = db.gw_messages
                .Where(m => m.shop_id == shop_id && !m.deleted && m.status == 1)
                .OrderByDescending(m => m.add_time).Skip(0).Take(5);
            if (message.Count()>0)
            {
                foreach (var item in message)
                {
                    item.status = 0;
                }
                await db.SaveChangesAsync();
                return true;
            }
            return false;
        }
    }
}
